<?php

namespace app\common\model;
use think\Model;
use think\Db;
use app\common\model\Prt;

class Member extends Model {
	protected $name = 'member';

	// 开启自动写入时间戳
	protected $autoWriteTimestamp = false;
	
/**
 * 付款后处理
 */
function dopay($out_trade_no){
	Db::startTrans();
	$paylog=db("mall_paylog")->where('sn', $out_trade_no)->find();
	$member=db("member")->find($paylog['uid']);
	$module=$paylog['type'];//pay代理join加盟商order订单
	try{
		$distibution=getDisbution();//获取分销设置
		$total_fee=0;//向会员上级累计返款
		if($module=="pay"){//代理付款
			db("member")->where('id', $paylog['uid'])->update(['distribution_type' => '2']);//修改用户为代理
			//向上级返现
			$this->fanxian_pay($paylog['id'],$member['mobile'],$member['id'],$member['pid'],1,$distibution,$total_fee);
			$dlfee=$distibution['montw']-$total_fee;//代理费用=用户支付推广佣金-向上级累计返款
			//更改支付日志状态为成功
		    db("mall_paylog")->where('sn', $out_trade_no)->update(['status' => '2','pt_id'=>$member['pt_id'],'pt_price'=>$dlfee]);
			//更新用户总代理钱包
			$this->mc_credit_inc($member, 'credit2', $dlfee, 0, '下级会员：'.$nickname.'支付申请合伙人成功奖励余额佣金',1,1);
		}
		if($module=="join"){//加盟商付款
			db("member")->where('id', $paylog['uid'])->update(['distribution_type' => '2']);//
			$this->fanxian_pay($paylog['id'],$member['mobile'],$member['id'],$member['pid'],1,$distibution);
			$dlfee=$distibution['montw']-$total_fee;//代理费用=用户支付推广佣金-向上级累计返款
			//更改支付日志状态为成功
		    db("mall_paylog")->where('sn', $out_trade_no)->update(['status' => '2','pt_id'=>$member['pt_id'],'pt_price'=>$dlfee]);
			//更新用户总代理钱包
			 $this->mc_credit_inc($member, 'credit2', $dlfee, 0, '下级会员：'.$nickname.'支付申请合伙人成功奖励余额佣金',1,1);
		}
		if($module=="order"){//修改订单状态
			$order=db("mall_order")->where('sn', $out_trade_no)->find();
			if($order["express_type"]==1){
				$restlt = db('mall_order')->where('sn', $out_trade_no)->update(['order_state' => 3]);
				if($order['goods_lanmu'] !=4){
					$prt=new Prt();	
					$prt->print_order($paylog);
				}
			}else{
				//o2o订单
				$restlt = db('mall_order')->where('sn', $out_trade_no)->update(['order_state' =>7]);
			}
			
		}
	    Db::commit();    
	} catch (\Exception $e) {
	    // 回滚事务
	    Db::rollback();
	}
	return $member;
}
//会员上级返现
function fanxian_pay($paylog_id,$nickname="",$uid,$parent_id=NULL,$level=1,$distibution,&$total_fee){
    if($level <= 3){		
        if(is_null($parent_id)){
            $parent_id = db("member")->where("id",$uid)->column('pid');
            if(empty($parent_id)){
                return false;
            }
        }
		$member = db('member')->where('id',$parent_id)->find();        
        if($member['distribution_type'] == 2){
            $price =$distibution[$level.'_money']; 
			$total_fee+=$price;
            $this->mc_credit_inc($member, 'credit2', $price, 0, '下级会员：'.$nickname.'支付申请合伙人成功奖励余额佣金',1);
            $paylog = array();
            $paylog['member'.$level] = $parent_id;
            $paylog['price'.$level] = $price;
			db("mall_paylog")->where('id', $paylog_id)->update($paylog);
            
//          $notice = '下级会员：'.$nickname.'支付申请合伙人成功奖励余额佣金'.$price;
//          mc_notice($notice,3,$parent_id);
        }
        if($member['pid']){
        	$this->fanxian_pay($paylog_id,$member['mobile'],$uid,$member['pid'],$level+1,$distibution,$total_fee);
        }
    }
}
	//订单收货向上级返现
	function mc_fanxian($nickname, $order,  $level = 1) {
		if ($level <= 3) {
	   	  $member = db('member')->find($order["level".$level]);        
		  if($member['distribution_type'] == 2){
				  $price =$order["level".$level.'_money'];
	              $this->mc_credit_inc($member, 'credit2', $price, 0, '下级会员：'.$nickname.'商品销售奖励佣金',0,0,1);
	      }
		  if($level<3){
		  	if($order["level".($level+1).'_money']!=0){
	      	  $this->mc_fanxian($nickname,$order,$level+1);
	     	}
		  }
		}
	}
	//记录代理商积分变化日志
/**
 *int 			$agent_id	商户ID
 *string 		$message	余额变化说明
 *int			$score	积分变化的值（可为正数或者负数）
 *boolean
 */
function insscoch($agent_id,$message,$score,$type,$tid=0){
	$agent =db('mall_agent')->find($agent_id); 
	if($agent){			
		$data = array();
		$data['agent_id'] = $agent_id;
		$data['message'] = $message;
		$data['type'] = $type;
		$data['tid'] = $tid;
		$data['score'] = $score;
		$data['add_time'] = now_time();
		db('mall_score_charge')->insert($data);
		$res=Db::execute('update long_mall_agent set `score` = `score` + '.$score.' where id = '.$agent_id);
		return $res;
	}else{
		return false;
	}
}
/**
 * 添加线上会员
 */
function add($mobile,$pid){
	$member = db('member')->where('mobile',$mobile)->find();
	if(!$member){
		$data['add_time'] = now_time();
		$data['mobile'] = $mobile;
		$data['pid'] =$pid;
		$data['password']=md5_salt(substr(input('mobile'), -6));
		$data['pay_password']=md5_salt(substr(input('mobile'), -6));
		$result = db('member')->insert($data);
	}   
}
	/**
	 * 记录用户金额变化
	 */
	function mc_credit_inc($member, $credittype, $value, $operator = 0, $remark = '',$type=0,$tid=0,$is_pt=0){
		$credit = floatval($member[$credittype]);
		if ($credit >= 0 && ($credit + $value >= 0)) {
			$data = array($credittype => $credit + $value);
			$res=db("member")->where("id",$member['id'])->update($data);//更新用户金额
		} //else {
			//return error('-1',"{$creditname}不足,无法操作");
		//}
		$data = array(
			'uid' => $member['id'],
			'credittype' => $credittype,
			'price' => currency_format($value),
			'add_time' => now_time(),
			'operator' => intval($operator),
			'remark' => $remark,
		    'type' => $type,
		    'tid' => $tid,
		    "is_pt"=>$is_pt
		);
		db('mall_credits')->insert($data);
		
		if($type == 1 && $credittype == 'credit2'){
		    Db::execute('update long_member set `all_balance` = `all_balance` + '.$value.' where id = '.$member['id']);
		}
		return true;
	}
	//记录代理商余额变化日志
	/**
	 *int 			$agent_id	商户ID
	 *string 		$message	余额变化说明
	 *float(10,2)	$balance	余额变化的值（可为正数或者负数）
	 *boolean 
	 */
	
	function insbalch($agent_id,$message,$balance,$type,$tid=0,$from=1){
		$agent =db('mall_agent')->find($agent_id); 
		if($agent){			
			$data = array();
			$data['agent_id'] = $agent_id;
			$data['message'] = $message;
			$data['type'] = $type;
			$data['tid'] = $tid;
			$data['balance'] = sprintf("%.2f",$balance);
			$data['add_time'] = now_time();
			$data['from'] = $from;
			db('mall_charge')->insert($data);
			Db::execute('update long_mall_agent set `store_balance` = `store_balance` + '.$balance.' where id = '.$agent_id);
		}
	}
		
	/**
	 * 记录总代理余额变化日志
	 * @param int $uid			总代理商ID
	 * @param string $message	余额变化明细
	 * @param float $balance	变化余额的值
	 */
	function insbalchuser($uid,$message,$balance,$type,$tid=0){
		$user = $this->find($uid);
			if($user){
				$data = array(
				'uid' => $uid,
				'credittype' => 'credit2',
				'price' => $balance,
				'add_time' => now_time(),
				'operator' => 0,
				'remark' => $message,
			    'type' => $type,
			    'tid' => $tid,
			    "is_pt"=>1
			);
			db('mall_credits')->insert($data);
			Db::execute('update long_member set `all_balance` = `all_balance` + '.$balance.' where id = '.$uid);
		}
	}
	
}
